package com.xbts.system.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alipay.api.domain.OrderItem;
import com.xbts.common.core.domain.Setting;
import com.xbts.common.core.domain.entity.SysUser;
import com.xbts.common.enums.SettingEnum;
import com.xbts.common.utils.DateUtils;
import com.xbts.common.utils.StringUtils;
import com.xbts.system.domain.CnBalanceOrder;
import com.xbts.system.domain.CnOrder;
import com.xbts.system.domain.CnOrderItem;
import com.xbts.system.domain.WeChatTemplateMsg;
import com.xbts.system.enums.CnWeChatTemplateMsgEnum;
import com.xbts.system.enums.OrderStatusEnum;
import com.xbts.system.service.ICnWeChatTemplateMsgService;
import com.xbts.system.service.ISysUserService;
import com.xbts.system.service.SettingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class CnWeChatTemplateMsgServiceImpl implements ICnWeChatTemplateMsgService {

    @Autowired
    private SettingService settingService;
    @Autowired
    private ISysUserService sysUserService;

    @Override
    public void sendTemplateMsg(String openId, String templateId, Map<String, WeChatTemplateMsg> sendMag) {
// 模板参数

        // openId代表一个唯一微信用户，即微信消息的接收人
//        if(StringUtils.isBlank(openId)){
//            openId = "osKpa6-NsxfloP4xpo1HqDo7EszY";
//        }
        // 公众号的模板id(也有相应的接口可以查询到)
//        templateId = "cTwYFnF-8OdOBDemOnfwAQg-Qz5b5RZcYphonW4ZpTU";
        // 微信的基础accessToken
        String accessToken = getAccessToken();
        System.out.println("accessToken-:" + accessToken);
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;

//        sendMag.put("character_string1", new WeChatTemplateMsg("SN11111"));
//        sendMag.put("thing3", new WeChatTemplateMsg("下单套餐！！"));
//        sendMag.put("time5", new WeChatTemplateMsg(DateUtils.getTime()));
//        sendMag.put("amount13", new WeChatTemplateMsg("10.33"));
        RestTemplate restTemplate = new RestTemplate();
        //拼接base参数
        Map<String, Object> sendBody = new HashMap<>();
        sendBody.put("touser", openId);               // openId
//        sendBody.put("url", "https://www.baidu.com");  //跳转网页url
        sendBody.put("data", sendMag);                   // 模板参数
        sendBody.put("template_id", templateId);      // 模板Id
        log.info("消息体是: {}",sendBody);
        ResponseEntity<String> response = restTemplate.postForEntity(requestUrl, sendBody, String.class);
        log.info("结果是: {}",response.getBody());
        JSONObject jsonObject = JSONObject.parseObject(response.getBody());
        String messageCode = jsonObject.getString("errcode");
        String msgId = jsonObject.getString("msgid");
        System.out.println("messageCode : " + messageCode + ", msgId: " +msgId);
    }

    @Override
    public void sendRealNameAuthenticationNotificationMsg(String userId, String time, String status) {
        String openId = getOpenId(userId);
        if (StringUtils.isNotBlank(openId)){
            Map<String, WeChatTemplateMsg> sendMag = new HashMap<>();
            sendMag.put("time2", new WeChatTemplateMsg(time));
            sendMag.put("const3", new WeChatTemplateMsg(status));
            sendTemplateMsg(openId, CnWeChatTemplateMsgEnum.REAL_NAME_AUTHENTICATION_NOTIFICATION.getDescription(), sendMag);
        }
    }

    @Override
    public void sendDeviceAlarmReminderMsg(String userId, String orderNo, String orderName, String becomeDueTime) {
        String openId = getOpenId(userId);
        if (StringUtils.isNotBlank(openId)){
            Map<String, WeChatTemplateMsg> sendMag = new HashMap<>();
            sendMag.put("character_string21", new WeChatTemplateMsg(orderNo));
            sendMag.put("thing3", new WeChatTemplateMsg(orderName));
            sendMag.put("time35", new WeChatTemplateMsg(becomeDueTime));
            sendTemplateMsg(openId, CnWeChatTemplateMsgEnum.DEVICE_ALARM_REMINDER.getDescription(), sendMag);
        }

    }

    @Override
    public void sendReminderOfSuccessfulRechargeMsg(String userId, CnBalanceOrder balanceOrder) {
        SysUser user = sysUserService.selectUserById(Long.valueOf(userId));
        String openId = user.getWechatOpenId();
        if (StringUtils.isNotBlank(openId)){
            Map<String, WeChatTemplateMsg> sendMag = new HashMap<>();
            sendMag.put("character_string2", new WeChatTemplateMsg(balanceOrder.getSn()));
            sendMag.put("thing4", new WeChatTemplateMsg(balanceOrder.getPaymentMethod().getPaymentName()));
            sendMag.put("amount5", new WeChatTemplateMsg(balanceOrder.getAmount().toString()));
            sendMag.put("time11", new WeChatTemplateMsg(DateUtils.getTime()));
            sendMag.put("amount6", new WeChatTemplateMsg(user.getUserWallet().toString()));
            sendTemplateMsg(openId, CnWeChatTemplateMsgEnum.REMINDER_OF_SUCCESSFUL_RECHARGE.getDescription(), sendMag);
        }
    }

    @Override
    public void sendOrderReviewResultNotificationMsg(String userId, CnOrderItem orderItem) {
        String openId = getOpenId(userId);
        if (StringUtils.isNotBlank(openId)){
            Map<String, WeChatTemplateMsg> sendMag = new HashMap<>();
            sendMag.put("character_string7", new WeChatTemplateMsg(orderItem.getSn()));
            sendMag.put("thing9", new WeChatTemplateMsg(orderItem.getOrderAbstract().length() < 20 ? orderItem.getOrderAbstract() : orderItem.getOrderAbstract().substring(0, 16) + "..."));
            // TODO 判断审核状态
            if(orderItem.getOrderStatus().equals(OrderStatusEnum.SUCCESS)){
                sendMag.put("const5", new WeChatTemplateMsg("审核通过"));
            } else {
                sendMag.put("const5", new WeChatTemplateMsg("审核未通过"));
            }

            sendMag.put("time4", new WeChatTemplateMsg(DateUtils.getTime()));
            sendTemplateMsg(openId, CnWeChatTemplateMsgEnum.ORDER_REVIEW_RESULT_NOTIFICATION.getDescription(), sendMag);
        }
    }

    @Override
    public void sendPendingOrderNotificationMsg(String userId, CnOrder order) {
        String openId = getOpenId(userId);
        if (StringUtils.isNotBlank(openId)){
            Map<String, WeChatTemplateMsg> sendMag = new HashMap<>();
            sendMag.put("character_string1", new WeChatTemplateMsg(order.getSn()));
            sendMag.put("thing3", new WeChatTemplateMsg(order.getOrderAbstract().length() < 20 ? order.getOrderAbstract() : order.getOrderAbstract().substring(0, 16) + "..."));
            sendMag.put("time5", new WeChatTemplateMsg(DateUtils.getTime()));
            sendMag.put("amount13", new WeChatTemplateMsg(order.getUpdatePrice().toString()));
            sendTemplateMsg(openId, CnWeChatTemplateMsgEnum.PENDING_ORDER_NOTIFICATION.getDescription(), sendMag);
        }
    }

    String getOpenId(String userId){
        SysUser user = sysUserService.selectUserById(Long.valueOf(userId));
        if (StringUtils.isNull(user)){
            return null;
        }
        return user.getWechatOpenId();
    }

    // 获取微信基础accessToken
    public String getAccessToken(){
        Setting setting = settingService.get(SettingEnum.WECHAT_PUBLIC_PLATFORM_SETTING.name());
        String settingValue = setting.getSettingValue();
        JSONObject jsonObj = JSON.parseObject(settingValue);

        String appId = jsonObj.getString("AppId");
        String appSecret = jsonObj.getString("AppSecret");
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ appId +"&secret=" + appSecret;
        String res = HttpUtil.get(requestUrl);
        JSONObject jsonObject = JSONObject.parseObject(res);
        String accessToken = jsonObject.getString("access_token");
        return accessToken;
    }

}
